//
//  AYPullDownToRefreshControl.swift
//  iOSSinaWeb
//
//  Created by yws on 16/5/25.
//  Copyright © 2016年 yws. All rights reserved.
//

import UIKit

private let AYPullDownToRefreshControlHeight:CGFloat = 60


///定义状态枚举
enum AYPullDownToRefreshStatus {
    case Normal
    case Pulling
    case Refreshing
    
}

class AYPullDownToRefreshControl: UIView {
    
    var pullDownToRefreshCallback: (() -> ())?
    
    //公开方法
    
    ///结束刷新
    func endRefresh() {
        if currentStatus == .Refreshing {
            currentStatus = .Normal
            
            UIView.animateWithDuration(AYDefaultDuration, animations: { 
                self.superScrollView?.contentInset.top -= AYPullDownToRefreshControlHeight
            })
        }
    }
    
    ///开始刷新
    func beginRefreshing() {
        currentStatus = .Refreshing
    }
    
    //父控件
    private var superScrollView: UIScrollView?
    
    ///记录当前状态
    private var currentStatus: AYPullDownToRefreshStatus = AYPullDownToRefreshStatus.Normal {
        didSet{
            switch currentStatus {
            case .Normal:
                fhlView.layer.removeAllAnimations()
                fhlView.hidden = true
                arrowView.hidden = false
                messageLabel.text = "下拉刷新"
                UIView.animateWithDuration(AYDefaultDuration, animations: { 
                    self.arrowView.transform = CGAffineTransformIdentity
                })
                
            case .Pulling:
                messageLabel.text = "释放刷新"
                UIView.animateWithDuration(AYDefaultDuration, animations: { 
                    self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                arrowView.hidden = true
                fhlView.hidden = false
                messageLabel.text = "正在刷新"
                
                let rotationAnim = CABasicAnimation(keyPath:"transform.rotation")
                rotationAnim.toValue = M_PI * 2
                rotationAnim.duration = AYDefaultDuration * 3
                rotationAnim.repeatCount = MAXFLOAT
                rotationAnim.removedOnCompletion = false
                
                fhlView.layer.addAnimation(rotationAnim, forKey: "rotationAnim")
                
                UIView.animateWithDuration(AYDefaultDuration, animations: { 
                    self.superScrollView?.contentInset.top += AYPullDownToRefreshControlHeight
                })
                
                pullDownToRefreshCallback?()
            }
        }
    }
    
    
    private let NormalToPullingOffset:CGFloat = -124
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 外面创建直接调用[[CZPullDownToRefreshControl alloc] init] -> init(frame: CGRect)
    override init(frame: CGRect) {
        let newFrame = CGRect(x: 0, y: -AYPullDownToRefreshControlHeight, width: UIScreen.mainScreen().bounds.width, height: AYPullDownToRefreshControlHeight)
        super.init(frame: newFrame)
        
        preapreUI()
    }
    
    private func preapreUI() {
//        backgroundColor = UIColor.brownColor()
        
        fhlView.hidden = true
        addSubview(fhlView)
        addSubview(messageLabel)
        addSubview(arrowView)
        
        //添加约束
        arrowView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self).offset(-30)
            make.centerY.equalTo(self)
        }
        
        
        fhlView.snp_makeConstraints { (make) in
            make.centerX.centerY.equalTo(arrowView)
        }
        
        messageLabel.snp_makeConstraints { (make) in
            make.leading.equalTo(arrowView.snp_trailing).offset(10)
            make.centerY.equalTo(self)
        }
        
    }
    
    
    //下拉刷新控件是否添加到了tableView里面
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        if let superScrollView = newSuperview as? UIScrollView {
            self.superScrollView = superScrollView
            superScrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        }
    }
    
    ///移除监听
    deinit{
        superScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if superScrollView!.dragging {
            if currentStatus == .Pulling && superScrollView?.contentOffset.y > NormalToPullingOffset{
                currentStatus = .Normal
                AMPrint(items: "切换到normal")
            } else if currentStatus == .Normal && superScrollView?.contentOffset.y < NormalToPullingOffset{
                currentStatus = .Pulling
                AMPrint(items: "切换到Pulling")
            }
        } else {
            if currentStatus == .Pulling {
                currentStatus = .Refreshing
                AMPrint(items: "刷新")
            }

    }
}
    ///懒加载图片
    private lazy var arrowView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    ///刷新状态时的图片
    private lazy var fhlView: UIImageView = UIImageView(image: UIImage(named: "tableview_loading"))
    ///Label
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        
        label.font = UIFont.systemFontOfSize(14)
        label.text = "下拉刷新"
        label.sizeToFit()
        label.textColor = UIColor.darkGrayColor()
        return label
    }()
}








